#!/usr/bin/env node

import { execSync } from 'child_process';
import { readdirSync, readFileSync, existsSync, statSync } from 'fs';
import { join } from 'path';

// 检查是否在Docker环境中
const isDocker =
  process.env.SKIP_POSTINSTALL === 'true' ||
  process.env.DOCKER_BUILDKIT === '1' ||
  process.env.IN_DOCKER === 'true';

if (isDocker) {
  console.log('🚀 Docker build detected, skipping postinstall script');
  process.exit(0);
}

// 检查包是否有stub脚本
function hasStubScript(packagePath) {
  try {
    const packageJsonPath = join(packagePath, 'package.json');
    if (!existsSync(packageJsonPath)) {
      return false;
    }

    const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
    return packageJson.scripts && packageJson.scripts.stub;
  } catch (error) {
    return false;
  }
}

// 检查包是否需要重新生成stub
function needsStubRegeneration(packagePath) {
  try {
    const packageJsonPath = join(packagePath, 'package.json');
    const distPath = join(packagePath, 'dist');

    // 如果dist目录不存在，需要生成
    if (!existsSync(distPath)) {
      return true;
    }

    // 获取package.json的修改时间
    const packageJsonStat = statSync(packageJsonPath);

    // 获取dist目录的修改时间
    const distStat = statSync(distPath);

    // 如果package.json比dist目录新，需要重新生成
    if (packageJsonStat.mtime > distStat.mtime) {
      return true;
    }

    // 检查src目录是否存在，如果存在则比较src目录的修改时间
    const srcPath = join(packagePath, 'src');
    if (existsSync(srcPath)) {
      const srcStat = statSync(srcPath);
      if (srcStat.mtime > distStat.mtime) {
        return true;
      }
    }

    // 检查tsconfig.json的修改时间
    const tsconfigPath = join(packagePath, 'tsconfig.json');
    if (existsSync(tsconfigPath)) {
      const tsconfigStat = statSync(tsconfigPath);
      if (tsconfigStat.mtime > distStat.mtime) {
        return true;
      }
    }

    // 检查build.config.ts的修改时间
    const buildConfigPath = join(packagePath, 'build.config.ts');
    if (existsSync(buildConfigPath)) {
      const buildConfigStat = statSync(buildConfigPath);
      if (buildConfigStat.mtime > distStat.mtime) {
        return true;
      }
    }

    return false;
  } catch (error) {
    // 如果出现错误，为了安全起见，重新生成
    return true;
  }
}

// 获取所有工作区包路径
function getWorkspacePackages() {
  const workspaces = [
    'packages/*',
    'packages/server/*',
    'packages/frontend/*',
    'apps/*',
    'tools/*',
  ];

  const packages = [];

  for (const pattern of workspaces) {
    try {
      const baseDir = pattern.split('/*')[0];
      const subDirs = readdirSync(baseDir, { withFileTypes: true });

      for (const dir of subDirs) {
        if (dir.isDirectory()) {
          const packagePath = join(baseDir, dir.name);
          if (hasStubScript(packagePath)) {
            packages.push(packagePath);
          }
        }
      }
    } catch (error) {
      // 忽略不存在的目录
    }
  }

  return packages;
}

try {
  console.log('🔧 Running postinstall script for local development...');
  console.log('📦 Checking stub files for workspace packages...');

  // 获取有stub脚本的包
  const packagesWithStub = getWorkspacePackages();
  console.log(`📋 Found ${packagesWithStub.length} packages with stub scripts`);

  let regeneratedCount = 0;
  let cachedCount = 0;

  // 为每个有stub脚本的包检查并运行stub命令
  for (const packagePath of packagesWithStub) {
    try {
      if (needsStubRegeneration(packagePath)) {
        console.log(`🔨 Regenerating stub for ${packagePath}...`);
        execSync('pnpm unbuild --stub', {
          stdio: 'inherit',
          cwd: packagePath,
        });
        console.log(`✅ Stub regenerated for ${packagePath}`);
        regeneratedCount++;
      } else {
        console.log(`💾 Using cached stub for ${packagePath}`);
        cachedCount++;
      }
    } catch (error) {
      console.warn(`⚠️  Stub failed for ${packagePath}: ${error.message}`);
    }
  }

  console.log(
    `📊 Stub generation summary: ${regeneratedCount} regenerated, ${cachedCount} cached`,
  );
  console.log('✅ Postinstall completed successfully');
} catch (error) {
  console.warn('⚠️  Postinstall script failed, but continuing...');
  console.warn('   This is usually not critical for development');
  console.warn(`   Error: ${error.message}`);

  // 在开发环境中，postinstall失败不应该阻止安装
  if (process.env.NODE_ENV === 'production') {
    process.exit(1);
  }
}
